package main

import (
	"encoding/json"
	"fmt"
	"log"
	"net/http"
	"os"
	"ups/dbs"
	"ups/tools"
)

type RespData struct {
	Error error `json:"error"`
	Data  any   `json:"data"`
}

type ReqData struct {
	Value string `json:"value"`
	Token string `json:"token"`
}

func HomePage(w http.ResponseWriter, r *http.Request) {
	json.NewEncoder(w).Encode(RespData{
		Error: nil,
		Data:  "欢迎使用自动升级服务器！",
	})
}

func GetFiles(w http.ResponseWriter, r *http.Request) {
	log.Println(">GET:", r.RemoteAddr)
	var dat ReqData
	err := json.NewDecoder(r.Body).Decode(&dat)
	if err != nil {
		w.WriteHeader(http.StatusInternalServerError)
		w.Write([]byte(err.Error()))
		return
	}

	if !tools.CheckToken(dat.Value, dat.Token) {
		json.NewEncoder(w).Encode(RespData{
			Error: fmt.Errorf("Token检测失败，请使用合法的客户端！"),
			Data:  nil,
		})
		return
	}
	files := dbs.GetFiles(dat.Value)
	w.WriteHeader(http.StatusOK)
	json.NewEncoder(w).Encode(RespData{
		Error: nil,
		Data:  files,
	})
}

func GetContent(w http.ResponseWriter, r *http.Request) {
	var dat ReqData
	err := json.NewDecoder(r.Body).Decode(&dat)
	if err != nil {
		w.WriteHeader(http.StatusInternalServerError)
		w.Write([]byte(err.Error()))
		return
	}
	if !tools.CheckToken(dat.Value, dat.Token) {
		json.NewEncoder(w).Encode(RespData{
			Error: fmt.Errorf("Token检测失败，请使用合法的客户端！"),
			Data:  nil,
		})
		return
	}
	file := dbs.GetContent(dat.Value)
	w.WriteHeader(http.StatusOK)
	json.NewEncoder(w).Encode(RespData{
		Error: nil,
		Data:  file,
	})
}

func PathExists(path string) bool {
	_, err := os.Stat(path)
	return err == nil
}

func HandleRequests(host string, port int64) {
	http.HandleFunc("/", HomePage)
	http.HandleFunc("/files", GetFiles)
	http.HandleFunc("/content", GetContent)
	addr_port := fmt.Sprintf("%v:%d", host, port)
	log.Println(http.ListenAndServe(addr_port, nil))
}
